package com.wngbms.demo.config;

import com.wngbms.demo.annotation.DataBase;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect implements Ordered {


    @Pointcut("@annotation(com.wngbms.demo.annotation.DataBase)")
    public void dataSourcePointCut() {

    }

    @Before("dataSourcePointCut()")
    public void beforeDetermineDb(JoinPoint point) throws NoSuchMethodException {

        Class<?> aClass = point.getTarget().getClass();
        String name = point.getSignature().getName();
        Class[] argClass = ((MethodSignature) point.getSignature()).getParameterTypes();

        String dataSource = DatabaseContextHolder.MASTER;
        Method method = aClass.getMethod(name, argClass);
        if (method.isAnnotationPresent(DataBase.class)) {
            DataBase annotation = method.getAnnotation(DataBase.class);
            dataSource = annotation.value();
        }

        DatabaseContextHolder.setDatabaseType(dataSource);
    }

    @After("dataSourcePointCut()")
    public void afterDetermineDb(JoinPoint point) {
        DatabaseContextHolder.clearDataSource();
    }

    @Override
    public int getOrder() {
        return 1;
    }

}
